<?php

namespace app\api\model;

use app\common\model\Token;
use app\exceptions\ApiException;
use ba\IdNamePhone;
use EasyWeChat\Factory;
use think\facade\Log;
use think\Model;

/**
 * Member
 */
class Member extends Model
{
    // 表名
    protected $name = 'member';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    public function getAvatarAttr($val){
        return full_url($val,true,config('buildadmin.default_avatar'));
    }


    public function getUser($params){
        $member_id = $params['member_id'];
        $user = self::where(['id' => $member_id])
            ->field('id,avatar,nickname,phone,is_hotel,username,id_number')
            ->find();

        $user['avatar'] = full_url($user['avatar'],true,config('buildadmin.default_avatar'));
        $user['username'] = $user['username'] ?? '';
        $user['id_number'] = $user['id_number'] ?? '';

        return api_message($user);
    }


    public function idNamePhone($params){
        $id = $params['id_number'] ?? '';
        $name = $params['username'] ?? '';
        if(!$id  || !$name) throw new ApiException('请填写完整的信息');
        $member_id = $params['member_id'];
        //查询该用户信息
        $member = self::where(['id' => $member_id])->find();
        if(!$member) throw new ApiException('用户不存在');
        $idNamePhone = self::where(['username' => $name,'id_number' => $id])->find();
        if($idNamePhone) throw new ApiException('您的身份信息已被认证,请使用新的身份证号！');

        $res = (new IdNamePhone())->IdNamePhone($id,$name,$member['phone']);
        if($res['state'] !== 1) throw new ApiException('手机号码认证信息需与身份信息一致');

        //更新信息
        if(!self::where(['id' => $member_id])->update(['username' => $name,'id_number' => $id])) throw new ApiException('操作失败');

        return api_message([],'认证成功');
    }



    public function wxLogin($params)
    {
        $iv = $params['iv'] ?? '';
        $encryptedData = $params['encryptedData'] ?? '';
        $code = $params['code'] ?? '';
        if (!$code || !$iv || !$encryptedData) {
            throw  new ApiException('参数错误');
        }
        // 获取授权appid
        $app = Factory::miniProgram(config('wechat.xcx'));
        $data = $app->auth->session($params['code']);
        if (!$data) {
            throw new ApiException('登录异常');
        }
        $session = $data['session_key'] ?? '';
        if (!$session) {
            throw new ApiException('登录失败');
        }
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);
        Log::info('wxLogin-请求信息:' . json_encode($decryptedData, JSON_UNESCAPED_UNICODE));
        $phone = $decryptedData['phoneNumber'] ?? '';
        if (!$phone) {
            throw new ApiException('获取手机号失败');
        }
        $userInfo = self::where(['phone' => $phone])->find();

        $ip = get_real_ip();
        $city = $this->getCity($ip);
        if (!$userInfo) {
            //用户不存在，创建用户
            $last_four_digits = substr($phone, -4);
            $insert['nickname'] = $params['nickName'] ?? '微信用户_' . $last_four_digits;
            $insert['openid'] = $data['openid'];
            $insert['create_time'] = time();
            $insert['phone'] = $phone ?? '';
            $insert['ip'] = $ip;
            $insert['city'] = $city;
            $userId = (new Member())->insertGetId($insert);

        } else {
            if ($userInfo['status'] == 0 && $userInfo['expire_time'] > time()) {
                $expire_time = $this->timeDifference($userInfo['expire_time']);
                throw  new ApiException('您的账号已被冻结,剩余时长:'.$expire_time);
            }
            (new Member())->where(['id' => $userInfo['id']])->update(['ip' => $ip,'city' => $city]);
            $userId = $userInfo['id'];
        }
        $wxUserMes['user_token'] = (new Token())->product_token($userId, 1);
        //获取用户信息
        $wxUserMes['uid'] = $userId;


        return api_message($wxUserMes, '登录成功');
    }


    public function getCity($ip)
    {
        $url = "http://ip-api.com/json/{$ip}?lang=zh-CN";
        $response = file_get_contents($url);
        $result = json_decode($response, true);
        if ($result['status'] == 'success') {
            return $result['city'];
        } else {
            return '';
        }
    }
    public function timeDifference($timestamp) {
        // 获取当前时间戳
        $currentTimestamp = time();
        // 计算时间差，单位秒
        $diff = $timestamp - $currentTimestamp;
        // 计算天数
        $days = floor($diff / (60 * 60 * 24));
        $diff -= $days * (60 * 60 * 24);
        // 计算小时数
        $hours = floor($diff / (60 * 60));
        $diff -= $hours * (60 * 60);
        // 计算分钟数
        $minutes = floor($diff / 60);
        $diff -= $minutes * 60;
        // 计算秒数
        $seconds = $diff;
        // 构造返回值
        $result = '';
        if ($days > 0) {
            $result .= $days . "天 ";
        }
        if ($hours > 0) {
            $result .= $hours . "小时 ";
        }
        if ($minutes > 0) {
            $result .= $minutes . "分钟 ";
        }
        if ($seconds > 0) {
            $result .= $seconds . "秒";
        }

        return $result;
    }




    public function updateUser($params){
        $avatar = $params['avatar'] ?? '';
        $nickname = $params['nickname'] ?? '';
        if (!$avatar) {
            throw new ApiException('请填上传头像');
        }

        if (!$nickname) {
            throw new ApiException('请填写昵称');
        }

        $avatar = $this->removeDomain($avatar);

        if (!self::where(['id' => $params['member_id']])->update(['nickname' => $nickname,'avatar' => $avatar])) {
            throw new ApiException('修改失败');
        }
        return api_message([], '修改成功');
    }

    public   function removeDomain($url)
    {
        if (strpos($url, "https://") === 0 || strpos($url, "http://") === 0) {
            // 分割 URL 来去除 https://
            $urlParts = explode('/', $url, 4); // 最多分割成四部分
            if (count($urlParts) > 3) {
                // 重新构建 URL，排除协议和域名部分
                return '/' . $urlParts[3];
            }
        }
        return $url; // 如果 URL 不以 https:// 开头，直接返回
    }
}
